package com.kristin.springboot;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;


public class SpringApplication {

    public static void run(Class clazz) {

        // 新建一个容器
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(clazz);
        webApplicationContext.refresh();

        // 启动服务器
        WebServer webServer = getWebService(webApplicationContext);
        webServer.start(webApplicationContext);
    }

    private static WebServer getWebService(WebApplicationContext webApplicationContext) {
        Map<String, WebServer> map = webApplicationContext.getBeansOfType(WebServer.class);
        if(map.size() == 0) {
            throw new RuntimeException("webServer not found");
        } else if(map.size() > 1) {
            throw new IllegalArgumentException("one more webServer found");
        }
        return map.values().stream().findFirst().get();
    }
}
